<script>
import addtable from "@/mixins/addtable";
import AjaxStore from "@/utils/store/proxyAjax";
import store from "./store";

export default {
  name: "procdef",
  mixins: [addtable, store],
  data() {
    return {
      tableSelectionCol: false,
      tableOptWidth: "120",
      labelWidth: "100px",
      defaultItemsLength: 6,
      startProcessUrl: "/v1/activiti/procdef/startProcessInstance",
      activateProcessUrl: "/v1/activiti/procdef/activate",
      suspendProcessUrl: "/v1/activiti/procdef/suspend",
      viewProcessUrl: "/v1/activiti/procdef/viewProcessDefImage",
      store: new AjaxStore({
        url: "/v1/activiti/procdef/query"
      }),
      columns: [
        {
          prop: "id",
          label: "流程ID",
          sortable: true,
          "min-width": "140",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "name",
          label: "流程名称",
          sortable: true,
          "min-width": "140",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "category",
          label: "类别",
          sortable: true,
          width: "240",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "key",
          label: "关键字",
          sortable: true,
          "min-width": "140",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "version",
          label: "版本",
          sortable: true,
          width: "120",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "suspensionState",
          label: "状态",
          sortable: true,
          width: "80",
          formatter: (row, column, cellValue) =>
            cellValue === 1 ? "激活" : "挂起",
          "header-align": "center"
        }
      ],
      searchFields: [
        {
          label: "流程定义ID",
          prop: "processDefinitionId",
          placeholder: "请输入流程定义ID",
          anchor: 9
        },
        {
          label: "流程定义名称",
          prop: "processDefinitionName",
          placeholder: "请输入流程定义名称",
          anchor: 12
        },
        {
          label: "关键字",
          prop: "processDefinitionKey",
          placeholder: "请输入流程定义关键字",
          anchor: 9
        },
        {
          label: "流程状态",
          clearable: true,
          prop: "processStatus",
          xType: "select",
          anchor: 10,
          placeholder: "请选择流程状态",
          xStore: [
            { label: "激活", value: 1 },
            { label: "挂起", value: 2 }
          ]
        },
        {
          label: "最近版本",
          prop: "isLatestVersion",
          xType: "checkbox",
          xStore: [{ label: "" }],
          anchor: 3
        }
      ],
      searchModel: {
        processDefinitionId: "",
        processDefinitionName: "",
        processDefinitionKey: "",
        processStatus: "",
        isLatestVersion: true
      },
      searchBtnList: this.searchBtns,
      toolPanelBtnList: [],
      formPanel: {
        start: {
          model: {
            processDefinitionId: "",
            name: "",
            businessKey: "",
            variables: ""
          },
          fields: [
            {
              label: "流程名称",
              prop: "name",
              placeholder: "",
              xType: "text",
              anchor: 24,
              disabled: false
            },
            {
              label: "关键字",
              prop: "businessKey",
              placeholder: "请输入关键字",
              anchor: 24,
              disabled: false
            },
            {
              label: "变量",
              prop: "variables",
              type: "textarea",
              rows: 5,
              anchor: 24,
              disabled: false,
              placeholder: `请输入对象，示例如下
{
  var1: “hello1”,
  var2: “hello2”
}`
            }
          ],
          rules: {},
          title: "启动流程",
          type: "START",
          ref: "startForm",
          submitBtnList: this.startBtns
        }
      }
    };
  },
  methods: {
    handleSearchReset(_data, _form) {
      this.$refs.searchForm.onReset();
      this.searchModel.isLatestVersion = false;
    },
    // 启动流程
    handleStartProcess(row) {
      this.dialogType = "START";
      this.$nextTick(() => {
        this.$refs.startFrom && this.$refs.startForm.resetFields();
        this.$set(this.formPanel.start.model, "processDefinitionId", row["id"]);
        this.$set(this.formPanel.start.model, "name", row["name"]);
      });
    },
    // 提交启动流程
    handleStartProcessSubmit() {
      const params = {};
      Object.assign(params, this.formPanel.start.model);
      delete params.name;
      this.$refs.startFormSubmitBtns.handleChangeStatus(
        "handleStartProcessSubmit",
        { loading: true, icon: "" }
      );
      this.startProcess(params)
        .then(({ success }) => {
          this.$refs.startFormSubmitBtns.handleChangeStatus(
            "handleStartProcessSubmit",
            { loading: false, icon: "" }
          );
          this.$message({
            type: success ? "success" : "error",
            message: success ? "启动流程成功！" : "启动流程失败！"
          });
          if (success) {
            this.$refs.table.load(1);
            this.dialogType = "";
          }
        })
        .catch(err => {
          this.$refs.startFormSubmitBtns &&
            this.$refs.startFormSubmitBtns.handleChangeStatus(
              "handleStartProcessSubmit",
              { loading: false, icon: "" }
            );
          console.log(err);
        });
    },
    getData({ page, limit }) {
      this.searchModel.isLatestVersion
        ? this.store.read({
            start: page,
            limit: limit,
            q_isLatestVersion: true
          })
        : this.store.read({ start: page, limit: limit });
    },
    // 激活流程
    handleActivateProcess(row) {
      this.activateProcess({ processDefinitionId: row.id }).then(
        ({ success, message }) => {
          this.$message({
            type: success ? "success" : "error",
            message
          });
          if (success) {
            this.$refs.table.load(1);
          }
        }
      );
    },
    // 挂起流程
    handleSuspendProcess(row) {
      this.suspendProcess({ processDefinitionId: row.id }).then(
        ({ success, message }) => {
          this.$message({
            type: success ? "success" : "error",
            message
          });
          if (success) {
            this.$refs.table.load(1);
          }
        }
      );
    },
    // 查看流程图
    handleViewProcessDefImage(row) {
      this.$router.push({
        path: `/activiti/procdef/${row.id}`
      });
    },
    // eslint-disabled-next-line
    renderWrapTable(h) {
      return (
        <WrapTable
          ref="table"
          getData={this.getData}
          total={this.total}
          data={this.data}
          fields={this.columns}
          selectionCol={this.tableSelectionCol}
          indexCol={this.tableIndexCol}
          pagination={this.pagination}
          autoLoad={this.autoLoad}
          tooltip-effect="dark"
          border
          stripe
          default-sort={this.tableDefaultSort}
          on-selection-change={this.handleSelectionChange}
        >
          {this.searchBtnList && this.searchBtnList.length > 0 ? (
            <SearchForm
              items={this.searchFields}
              defaultItemsLength={this.defaultItemsLength}
              props-model={this.searchModel}
              slot="searchPanel"
              ref="searchForm"
            >
              <ButtonList
                operateBtnList={this.searchBtnList}
                props-model={this.searchModel}
              ></ButtonList>
            </SearchForm>
          ) : (
            ""
          )}

          <c-row slot="toolPanel" class="toolPanel">
            <c-col
              span={this.btnListWidthPercent}
              offset={this.btnListWidthOffset}
            >
              <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
            </c-col>
          </c-row>

          {this.haveTool ? (
            <c-table-column
              label="操作"
              align="center"
              slot="toolbar"
              fixed="right"
              width={this.tableOptWidth}
              {...{
                scopedSlots: {
                  default: scope => {
                    return (
                      <TableButtonList
                        operateBtnList={
                          scope.row.suspensionState === 1
                            ? this.tableRowSuspendBtns
                            : this.tableRowActivateBtns
                        }
                        props-model={scope.row}
                      />
                    );
                  }
                }
              }}
            />
          ) : (
            ""
          )}
        </WrapTable>
      );
    }
  },
  beforeCreate() {
    // 根据页面路由找出有权限访问的 url 数组
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    );

    this.searchBtns = [
      {
        label: "查询",
        methods: "handleSearch",
        url: "/v1/activiti/procdef/query",
        icon: "el-icon-search",
        type: "primary",
        disabled: false
      },
      {
        label: "重置",
        methods: "handleSearchReset",
        url: "",
        icon: "el-icon-refresh",
        type: "warning",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);

    this.tableRowSuspendBtns = [
      {
        label: "挂起",
        methods: "handleSuspendProcess",
        url: "/v1/activiti/procdef/suspend",
        icon: "el-icon-remove-outline",
        type: "primary",
        key: "start",
        align: "top-start",
        disabled: false
      },
      {
        label: "启动实例",
        methods: "handleStartProcess",
        url: "/v1/activiti/procdef/startProcessInstance",
        svgIcon: "startTask",
        type: "danger",
        key: "delete",
        align: "top-start",
        disabled: false
      },
      {
        label: "流程图",
        methods: "handleViewProcessDefImage",
        url: "/v1/activiti/procdef/viewProcessDefImage",
        icon: "el-icon-picture-outline",
        type: "primary",
        key: "delete",
        align: "top-start",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);

    this.tableRowActivateBtns = [
      {
        label: "激活",
        methods: "handleActivateProcess",
        url: "/v1/activiti/procdef/activate",
        svgIcon: "activate",
        type: "primary",
        key: "start",
        align: "top-start",
        disabled: false
      },
      {
        label: "启动实例",
        methods: "handleStartProcess",
        url: "/v1/activiti/procdef/startProcessInstance",
        svgIcon: "startTask",
        type: "danger",
        key: "delete",
        align: "top-start",
        disabled: false
      },
      {
        label: "流程图",
        methods: "handleViewProcessDefImage",
        url: "/v1/activiti/procdef/viewProcessDefImage",
        icon: "el-icon-picture-outline",
        type: "danger",
        key: "delete",
        align: "top-start",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);

    this.startBtns = [
      {
        label: "提交",
        methods: "handleStartProcessSubmit",
        url: "/v1/activiti/procdef/startProcessInstance",
        icon: "el-icon-circle-check-outline",
        type: "primary",
        disabled: false
      },
      {
        label: "取消",
        methods: "handleCancel",
        url: "",
        icon: "el-icon-circle-close-outline",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);
  }
};
</script>

<style lang="scss">
.procdef {
  box-sizing: border-box;
  .searchPanel {
    padding-bottom: 0;
    .search-btn-box {
      bottom: 0;
    }
    .el-col {
      &:nth-child(1) {
        .el-form-item__label {
          min-width: 80px;
        }
      }
      &:nth-child(3) {
        .el-form-item__label {
          min-width: 80px;
        }
      }
      &:nth-child(4) {
        .el-form-item__label {
          min-width: 94px;
        }
      }
    }
  }
}
</style>
